from flask import Flask, render_template, request,escape
import weather
from log_sys import log_request
app = Flask(__name__)

@app.route('/all_results', methods=['POST'])
def all_results() -> 'html':
    key = 'ac1c16d9ba930c1f889b26fb9a392c2f'
    color1 = request.form['color1']
    color2 = request.form['color2']
    city = request.form['city']
    title = '这里是查询的结果：'
    result_humidity = str(weather.all(key, city,output='JSON', extensions='base')['humidity'])
    result_winddirection = str(weather.all(key, city, output='JSON', extensions='base')['winddirection'])
    result_windpower = str(weather.all(key, city, output='JSON', extensions='base')['windpower'])
    result_temperature = str(weather.all(key, city, output='JSON', extensions='base')['temperature'])
    result_weather = str(weather.all(key, city, output='JSON', extensions='base')['weather'])
    result_reporttime = str(weather.all(key, city, output='JSON', extensions='base')['reporttime'])

    #日志系统
    results = str(weather.all(key, city, output='JSON', extensions='base'))
    log_request(request, results)

    return render_template('all_results.html',
                           the_title=title,
                           the_city=city,
                           the_color1=color1,
                           the_color2=color2,
                           humidity=result_humidity,
                           winddirection=result_winddirection,
                           windpower=result_windpower,
                           temperature=result_temperature,
                           weather=result_weather,
                           reporttime=result_reporttime,
                           )
#日志系统
@app.route('/viewlog')
def view_the_log() -> 'html':
    """display the contents of thr log file as a html table"""
    contents = []
    with open('weather.log','r') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))
    len(contents)
    titles = ('用户提交','远程地址','访问代理','用户结果')
    return render_template('viewlog.html',
                           the_title='日志系统后台',
                           the_row_title=titles,
                           the_data=contents)

@app.route('/')
@app.route('/home',methods=['GET','POST'])
def home():
    title = '欢迎来到天气查询空间~'
    return render_template("home.html",
                           the_title=title,)

@app.route('/search',methods=['GET','POST'])
def entry_page() -> 'html':
    title = '欢迎来到天气查询空间~'
    return render_template('weather_search.html',
                           the_title=title,)